package com.starrocks.task;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Random;

/**
 * 测试数据生成器
 * 用于自动生成测试数据，方便测试增量同步功能
 * 
 * 配置项：
 * test.data.generator.enabled=true/false  # 是否启用（默认false）
 * test.data.generator.table=表名          # 目标表名
 */
@Slf4j
@Component
@ConditionalOnProperty(name = "test.data.generator.enabled", havingValue = "true")
public class TestDataGenerator {

    @Autowired
    @Qualifier("starrocksJdbcTemplate")
    private JdbcTemplate starrocksJdbcTemplate;

    @Value("${test.data.generator.table:device_status_info}")
    private String targetTable;

    private final Random random = new Random();
    private final DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
    
    // 用于生成递增的ID
    private static long counter = System.currentTimeMillis() / 1000;

    /**
     * 每秒执行一次，插入一条测试数据
     */
    @Scheduled(fixedRate = 1000)
    public void generateTestData() {
        try {
            counter++;
            LocalDateTime now = LocalDateTime.now();
            
            // 生成测试数据（匹配实际表结构）
            String deviceId = "TEST_" + counter;
            String reportTime = now.format(formatter);
            String deviceName = "测试设备_" + counter;
            String netLinkId = "LINK_" + (random.nextInt(100) + 1);
            String deviceIp = generateRandomIp();
            String devType = getRandomDevType();
            String devVendor = getRandomVendor();
            String devVer = "v" + (random.nextInt(3) + 1) + "." + random.nextInt(10);
            String tiVer = "TI_" + (random.nextInt(100) + 1);
            int cpuUsed = random.nextInt(100);  // smallint: 0-100
            int memUsed = random.nextInt(100);  // smallint: 0-100
            String diskInfo = generateDiskInfoArray();  // ARRAY类型
            String monitorTrafficStatistic = generateTrafficArray();  // ARRAY类型
            int transTrafficSize = random.nextInt(1000);  // smallint
            int transTrafficSpeed = random.nextInt(100);  // smallint
            String devStatus = getRandomStatus();
            String devAlert = getRandomAlert();
            String returnRuleId = "RULE_" + (random.nextInt(10) + 1);
            String remark = "测试数据_" + counter;
            int importance = random.nextInt(5) + 1;  // 1-5
            String updateTime = now.format(formatter);
            int isDelete = 0;  // 默认未删除
            
            // 构建INSERT SQL（匹配实际表结构）
            String sql = String.format(
                "INSERT INTO %s (device_id, report_time, device_name, net_link_id, device_ip, " +
                "dev_type, dev_vendor, dev_ver, ti_ver, cpu_used, mem_used, disk_info, " +
                "monitor_traffic_statistic, trans_traffic_size, trans_traffic_speed, " +
                "dev_status, dev_alert, return_rule_id, remark, importance, update_time, is_delete) " +
                "VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)",
                targetTable
            );
            
            // 执行插入
            starrocksJdbcTemplate.update(
                sql,
                deviceId, reportTime, deviceName, netLinkId, deviceIp,
                devType, devVendor, devVer, tiVer, cpuUsed, memUsed, diskInfo,
                monitorTrafficStatistic, transTrafficSize, transTrafficSpeed,
                devStatus, devAlert, returnRuleId, remark, importance, updateTime, isDelete
            );
            
            log.info("✅ 生成测试数据 - ID: {}, CPU: {}%, MEM: {}%, 状态: {}, 告警: {}", 
                deviceId, cpuUsed, memUsed, devStatus, devAlert);
            
        } catch (Exception e) {
            log.error("❌ 生成测试数据失败", e);
        }
    }

    /**
     * 随机生成IP地址
     */
    private String generateRandomIp() {
        return String.format("192.168.%d.%d", 
            random.nextInt(255), 
            random.nextInt(255));
    }

    /**
     * 随机获取设备类型
     */
    private String getRandomDevType() {
        String[] types = {"服务器", "交换机", "路由器", "防火墙", "负载均衡"};
        return types[random.nextInt(types.length)];
    }

    /**
     * 随机获取设备厂商
     */
    private String getRandomVendor() {
        String[] vendors = {"华为", "思科", "华三", "中兴", "新华三"};
        return vendors[random.nextInt(vendors.length)];
    }

    /**
     * 生成磁盘信息ARRAY（StarRocks的ARRAY类型）
     * 格式：["disk1:500GB:300GB", "disk2:1TB:800GB"]
     */
    private String generateDiskInfoArray() {
        StringBuilder sb = new StringBuilder("[");
        int diskCount = random.nextInt(3) + 1; // 1-3个磁盘
        for (int i = 0; i < diskCount; i++) {
            if (i > 0) sb.append(",");
            int total = 500 + random.nextInt(1500); // 500-2000GB
            int used = random.nextInt(total);
            sb.append("\"disk").append(i + 1)
              .append(":").append(total).append("GB")
              .append(":").append(used).append("GB\"");
        }
        sb.append("]");
        return sb.toString();
    }
    
    /**
     * 生成流量统计ARRAY
     * 格式：["rx:1000MB", "tx:500MB", "total:1500MB"]
     */
    private String generateTrafficArray() {
        int rx = random.nextInt(10000);
        int tx = random.nextInt(10000);
        return String.format("[\"rx:%dMB\",\"tx:%dMB\",\"total:%dMB\"]", 
            rx, tx, rx + tx);
    }
    
    /**
     * 随机获取告警状态
     */
    private String getRandomAlert() {
        String[] alerts = {"无告警", "CPU告警", "内存告警", "磁盘告警", "网络告警"};
        int[] weights = {70, 10, 10, 5, 5}; // 权重：无告警70%，其他各10%或5%
        
        int rand = random.nextInt(100);
        int sum = 0;
        for (int i = 0; i < weights.length; i++) {
            sum += weights[i];
            if (rand < sum) {
                return alerts[i];
            }
        }
        return alerts[0];
    }

    /**
     * 随机获取设备状态
     */
    private String getRandomStatus() {
        String[] statuses = {"在线", "离线", "告警", "维护中"};
        int[] weights = {70, 10, 15, 5}; // 权重：在线70%，离线10%，告警15%，维护5%
        
        int rand = random.nextInt(100);
        int sum = 0;
        for (int i = 0; i < weights.length; i++) {
            sum += weights[i];
            if (rand < sum) {
                return statuses[i];
            }
        }
        return statuses[0];
    }
    
    /**
     * 手动触发更新某条数据（模拟数据变更）
     * 可以通过API调用此方法
     */
    public void updateTestData(String deviceId) {
        try {
            String sql = String.format(
                "UPDATE %s SET cpu_used = ?, mem_used = ?, dev_status = ?, dev_alert = ?, " +
                "trans_traffic_size = ?, trans_traffic_speed = ?, update_time = ? WHERE device_id = ?",
                targetTable
            );
            
            int cpuUsed = random.nextInt(100);
            int memUsed = random.nextInt(100);
            String devStatus = getRandomStatus();
            String devAlert = getRandomAlert();
            int transTrafficSize = random.nextInt(1000);
            int transTrafficSpeed = random.nextInt(100);
            String updateTime = LocalDateTime.now().format(formatter);
            
            int affected = starrocksJdbcTemplate.update(sql, 
                cpuUsed, memUsed, devStatus, devAlert, 
                transTrafficSize, transTrafficSpeed, updateTime, deviceId);
            
            if (affected > 0) {
                log.info("🔄 更新测试数据 - ID: {}, CPU: {}%, MEM: {}%, 状态: {}, 告警: {}", 
                    deviceId, cpuUsed, memUsed, devStatus, devAlert);
            }
        } catch (Exception e) {
            log.error("❌ 更新测试数据失败 - ID: {}", deviceId, e);
        }
    }
    
    /**
     * 手动触发软删除某条数据
     */
    public void softDeleteTestData(String deviceId) {
        try {
            String sql = String.format(
                "UPDATE %s SET is_delete = 1, update_time = ? WHERE device_id = ?",
                targetTable
            );
            
            String updateTime = LocalDateTime.now().format(formatter);
            int affected = starrocksJdbcTemplate.update(sql, updateTime, deviceId);
            
            if (affected > 0) {
                log.info("🗑️ 软删除测试数据 - ID: {}", deviceId);
            }
        } catch (Exception e) {
            log.error("❌ 软删除测试数据失败 - ID: {}", deviceId, e);
        }
    }
}

